package com.example.demo.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.example.demo.bean.dto.UserLoginDTO2;
import com.example.demo.bean.vo.RegisterByPhoneVO2;
import com.example.demo.bean.vo.UserLoginByPassVO;
import com.example.demo.entity.UsersInfo;
import com.example.demo.result.Result;
import com.example.demo.service.IUsersInfoService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 言浠
 * @since 2024-03-29
 */
@Api(tags = "用户信息接口3.0")
@RestController
@RequestMapping("/users-info")
public class UsersInfoController {

    @Resource
    private IUsersInfoService usersInfoService;

    /**
     * 根据手机号模糊查询用户
     * @param phone"
     * @return Result<List<UserLoginDTO2>>
     */
    @SaCheckLogin
    @GetMapping("/selectByPhone/{phone}")
    @ApiOperation(value = "根据手机号查询用户")
    @ApiOperationSupport(author = "言浠")
    @ApiImplicitParams(@ApiImplicitParam(name = "phone",value = "电话号码",required = true))
    public Result<List<UserLoginDTO2>> getUserByPhone(@PathVariable String phone){
        List<UserLoginDTO2> byPhone = usersInfoService.findByPhone(phone);
        return Result.success(byPhone).msg("查询成功");
    }

    @ApiOperationSupport(author = "言浠")
    @ApiOperation(value = "登录2.0")
    @PostMapping("/login")
    public Result<UserLoginDTO2> login(@Valid @RequestBody UserLoginByPassVO userLoginByPassVO) {
        UsersInfo usersInfo = new UsersInfo();
        BeanUtil.copyProperties(userLoginByPassVO, usersInfo);
        UserLoginDTO2 login = usersInfoService.login(usersInfo);

        //保存登录信息
        StpUtil.login(login.getUserId());
        //获取当前会话的token
        String tokenValue = StpUtil.getTokenValue();
        //设置token
        login.setToken(tokenValue);

        return Result.success(login).msg("登录成功");
    }

    /**
     * 新增
     * @param registerByPhoneVO2"
     * @return Result<String>
     */
    @ApiOperationSupport(author = "言浠")
    @ApiOperation(value = "注册账号2.0")
    @PostMapping("/add")
    public Result<String> add(@Valid @RequestBody RegisterByPhoneVO2 registerByPhoneVO2) {
        UsersInfo usersInfo = new UsersInfo();
        BeanUtil.copyProperties(registerByPhoneVO2, usersInfo);
        usersInfoService.register(usersInfo);
        return Result.success().msg("注册成功");
    }
}
